package services

import (
	"hg/models"
	"hg/pkg/database"
	"strconv"

	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 查询所有评论
func GetComment(c *gin.Context) {
	resp := models.GetDefaultResp()
	videoIDStr := c.Param("int")
	videoID, err := strconv.Atoi(videoIDStr)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid video ID"})
		return
	}
	comments, _ := database.GetCommentByVideoId(videoID)
	resp.Data = comments
	c.JSON(http.StatusOK, resp)
}

// 新增评论
func AddComment(c *gin.Context) {
	user := getUserInfo(c)
	resp := models.GetDefaultResp()
	comment := new(models.Comment)
	if err := c.ShouldBindJSON(&comment); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	comment.UserId = user.Id
	comment.ParentId = 0
	comment.Time = time.Now()
	database.InsertOneComment(comment)
	c.JSON(http.StatusOK, resp)
}

// 删除评论
func DeleteComment(c *gin.Context) {
	//user := getUserInfo(c)
	resp := models.GetDefaultResp()
	commentID := c.Param("int")
	//commentUserId := c.commentUserid

	// 检查评论是否存在
	err := database.DeleteComment(commentID)
	if err != nil {
		logrus.Error("评论不存在", err)
		return
	}

	// //检查用户是否有权限删除评论
	// if commentUserId != user.Id {
	// 	setApiError(c, http.StatusUnauthorized, resp, err)
	// 	return
	// }

	// 删除评论
	err = database.DeleteComment(commentID)
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	c.JSON(http.StatusOK, resp)
}
